package com.baizhi.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.ShearCaptcha;
import com.baizhi.service.AdminService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("admin")
@Slf4j
//该注解和@Data一样  都是lombok技术来简化我们开发的
// @Slf4j可以代替 private static Logger logger = LoggerFactory.getLogger(当前类.class);
public class AdminController {
    @Autowired
    private AdminService adminService;

    @RequestMapping("getCaptcha")
    public void getCaptcha(HttpSession session, HttpServletResponse response){
        //1、获得一个验证码对象  利用hutool工具类
        ShearCaptcha shearCaptcha = CaptchaUtil.createShearCaptcha(100, 30);
        //2、将验证码内容保存到session中
        String code = shearCaptcha.getCode();
        System.out.println("验证码内容："+code);
        log.info("验证码内容："+code);
        session.setAttribute("code",code);
        //3、将验证码对象响应给浏览器
        try {
            shearCaptcha.write(response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping("login")
    public Map login(String username,String password,String code,HttpSession session){
        Map map = new HashMap();
        String realcode = (String) session.getAttribute("code");
        if(realcode!=null && realcode.equals(code)){
            boolean b = adminService.login(username, password);
            if(b){
                map.put("flag",true);
                session.setAttribute("login",username);
            }else {
                map.put("flag",false);
                map.put("massge","账户或密码不正确");
            }
        }else {
            map.put("flag",false);
            map.put("massge","验证码不正确");
        }
        return map;
    }
}
